package yf.mall.service.impl;

import com.yf.response.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;
import yf.mall.common.Const;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.*;
import yf.mall.service.AccountService;
import yf.mall.service.LevelService;
import yf.mall.service.MallActService;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.service.StoresService;
import yf.mall.vo.ItemVo;
import yf.mall.vo.TicketVo;

/**
 * 活动Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Mon Nov 25 13:53:21 CST 2019
 */
@Service
public class MallActServiceImpl extends BaseServiceImpl<MallActEntity> implements MallActService {

    private MallActDao mallActDao;

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private OrderItemDao itemDao;

    @Autowired
    private PriceDao priceDao;

    @Autowired
    private AreaDao areaDao;

    @Autowired
    private LevelService levelService;

    @Autowired
    private MallCardDao mallCardDao;

    @Autowired
    private MallGoodsDao mallGoodsDao;
    @Autowired
    private AccountRecordDao accountRecordDao;

    @Autowired
    public void setDao(MallActDao mallActDao) {
        this.mallActDao = mallActDao;
        super.setBaseDao(mallActDao);
    }


    /**
     *
     *   @Override
     *     public List<UserVo> queryListVo(UserVo userVo) {
     *         return userDao.queryListVo(userVo);
     *     }
     *
     *     @Override
     *     public UserVo getVo(Long id) {
     *         return userDao.getVo(id);
     *     }

     @Override List<MallActVo> queryListVo(MallActVo mallActVo){
     return mallActDao.queryListVo(mallActVo);
     }

     @Override MallActVo getVo(Long id){
     return mallActDao.getVo(id);
     }
     **/


    /**内部方法**/

    /**
     * 分享奖励
     *
     * @param userId
     * @param orderNo
     * @param quantity
     * @param pid
     * @param reward
     * @param type
     * @param rewardType
     */
    private void rewardShare(Long userId, String orderNo, Integer quantity, String reward, int type, Integer rewardType) {
        Boolean isReward = false;

        if (rewardType != null && rewardType == MallActRewardTypeEnum.yes.getIndex()) {
            isReward = true;
        }

        String[] rewards = reward.split("_");
        UserEntity userEntity = userDao.get(userId);
        String name = userEntity.getName();
        for (int i = 0; i < rewards.length; i++) {

            BigDecimal tem = new BigDecimal(rewards[i]);
            tem = tem.multiply(new BigDecimal(quantity));
            if (userEntity == null) break;
            accountService.reward(userEntity.getId(), type, tem, name, orderNo, isReward, AccountRecordBusEnum.SHARE_REWARD.getIndex());
            //只有清货券奖励给自己
            if (type != AccountTypeEnum.CLEAR.getIndex()) {
                userEntity = userDao.get(userEntity.getPid());
            }
        }
    }

    /**
     * 触发区域活动
     *
     * @param orderNo
     * @param quantity
     * @param rewardType
     * @param userId
     * @param goods
     */
    public void fireAreaAct(String orderNo, String province, String city, String county, Integer quantity, Integer rewardType, Long userId, String reward, MallGoodsEntity goods) {
        Boolean isReward = false;
        if (rewardType == MallActRewardTypeEnum.yes.getIndex()) isReward = true;
        String[] addrs = new String[]{province, province + city, province + city + county};
        String[] rewards = reward.split("_");
//        LevelEntity base = this.levelDao.findBase();
//        PriceEntity priceEntity = this.priceDao.findByLevelIdAndGoodsId(base.getId(), goods.getId());
        //对每个产品进行各级代理的转账
        for (int i = 0; i < addrs.length; i++) {
            BigDecimal tem = new BigDecimal(rewards[i]);
         /*   if (goods.getSaleType().equals(MallGoodsSaleTypeEnum.AGENT.getIndex())) {
                tem = tem.multiply(new BigDecimal(quantity)).multiply(priceEntity.getPrice()).divide(new BigDecimal(1000));
            }else*/
            if (goods.getSaleType().equals(MallGoodsSaleTypeEnum.STORES.getIndex())) {
                tem = tem.multiply(new BigDecimal(quantity)).multiply(goods.getShopPrice()).divide(new BigDecimal(1000));
            } else if (goods.getSaleType() == MallGoodsSaleTypeEnum.AGENT.getIndex() && goods.getUserId() != null && !goods.getUserId().equals(Const.ADMIN_ID)) {
                //获取供货价格
                tem = tem.multiply(new BigDecimal(quantity)).multiply(goods.getSupplyPrice()).divide(new BigDecimal(1000));
            } else {
                tem = tem.multiply(new BigDecimal(quantity)).multiply(goods.getNowPrice()).divide(new BigDecimal(1000));
            }

            AreaEntity areaEntity = areaDao.findByName(addrs[i]);
            if (areaEntity == null) {
                continue;
            }
            UserEntity userEntity = userDao.get(userId);
            if (areaEntity.getId() != null) {
                accountService.reward(areaEntity.getUserId(), AccountTypeEnum.CASH.getIndex(), tem, userEntity.getName(), orderNo, isReward, AccountRecordBusEnum.AREA_REWARD.getIndex());
            }
        }
    }


    // 触发升级活动
//    private void fireLevelUpAct(Long userId) {
//        UserEntity userEntity = userDao.get(userId);
//        LevelEntity minLv = this.levelDao.findBase();
//        LevelEntity levelEntity = levelDao.findByUserId(userId);
//        //不是最低级别
//        if (!levelEntity.getLv().equals(minLv.getLv())) {
//            return;
//        }
//        // 万元大礼，一购买就自动成为代理
//        userEntity.setLevelId(levelDao.findVipBase().getId());
//        this.userDao.update(userEntity);
//    }

    /**
     * 取消升级
     *
     * @param userId
     */
//    private void cancelLevelUpAct(Long userId) {
//        UserEntity userEntity = userDao.get(userId);
//        LevelEntity minLv = this.levelDao.findBase();
//        LevelEntity levelEntity = levelDao.findByUserId(userId);
//        //最低级别 不做处理
//        if (levelEntity.getLv().equals(minLv.getLv())) {
//            return;
//        }
//        // 重制为最低级别
//        userEntity.setLevelId(levelDao.findBase().getId());
//        this.userDao.update(userEntity);
//    }

    /**
     * 重置提货卡
     *
     * @param orderEntity
     */
    private void reviewCard(String code) {
        MallCardEntity mallCardEntity = mallCardDao.findByCode(code);
        if (mallCardEntity == null) {
            return;
        }
        mallCardEntity.setUserId(null);
        mallCardEntity.setUpdateTime(null);
        mallCardDao.updateAll(mallCardEntity);
    }

    /**
     * 扣减订单的XX券 xx数量
     *
     * @param accountType return 实际消耗的券
     */
    private BigDecimal cutTicket(String orderNo, Long userId, Integer accountType, BigDecimal amount) {
        AccountEntity accountEntity = accountService.findByUserIdAndType(userId, accountType);
        BigDecimal tc = amount;
        //不足时就是余额
        if (accountEntity.getAmount().compareTo(tc) < 0) {
            tc = accountEntity.getAmount();
        }
        //扣减优惠券
        accountService.pay(userId, accountType, tc, orderNo);
        return tc;
    }

    /**
     * Long
     * 从活动中获取产品所可以用券信息
     *
     * @param goodsId
     * @return
     */
    public TicketVo getTicketVo(Long goodsId) {
        // MallActEntity mallActEntity = this.mallActDao.findByGoodsIdAndstatus(goodsId, MallActStatusEnum.OPEN.getIndex());
        SaleTypeInfoEntity saleTypeInfoEntity = saleTypeInfoDao.findByGoodsId(goodsId);
        TicketVo ticketVo = new TicketVo();
        if (saleTypeInfoEntity == null) {
            ticketVo.setCoupon(new BigDecimal(0));
            ticketVo.setPoint(new BigDecimal(0));
            ticketVo.setVoucher(new BigDecimal(0));
            ticketVo.setClear(new BigDecimal(0));
            return ticketVo;
        }
        ticketVo.setCoupon(saleTypeInfoEntity.getMaxCoupon());
        ticketVo.setPoint(saleTypeInfoEntity.getPoint());
        ticketVo.setVoucher(saleTypeInfoEntity.getMaxVoucher());
        ticketVo.setClear(saleTypeInfoEntity.getMaxClear());
        if (null == saleTypeInfoEntity.getPoint()) {
            ticketVo.setPoint(new BigDecimal(0));
        }
        if (null == saleTypeInfoEntity.getMaxVoucher()) {
            ticketVo.setVoucher(new BigDecimal(0));
        }
        if (null == saleTypeInfoEntity.getMaxCoupon()) {
            ticketVo.setCoupon(new BigDecimal(0));
        }
        if (null == saleTypeInfoEntity.getMaxClear()) {
            ticketVo.setClear(new BigDecimal(0));
        }
        return ticketVo;
    }

    @Override //根据goodsId删除活动
    @Transactional(rollbackFor = Exception.class)
    public void deleteGoodsIdBatch(Long[] goods) {
        mallActDao.deleteGoodsIdBatch(goods);
    }

    @Override
    public List<MallActEntity> findByGoodsName(String goodsName, String actName, Integer status) {
        return mallActDao.findByGoodsName(goodsName, actName, status);
    }

    @Autowired
    private LotteryCountDao lotteryCountDao;

    @Autowired
    private LotteryActDao lotteryActDao;

    /**
     * 外部方法实现
     **/

    @Override
    public MallActEntity findByGoodsIdAndstatus(Long goodsId, Integer status) {
        return mallActDao.findByGoodsIdAndstatus(goodsId, status);
    }

    @Override
    public void fire(MallOrderEntity orderEntity) {
        //没有支付
        if (orderEntity.getPayStatus() == null || orderEntity.getPayStatus().equals(MallOrderPayStatusEnum.NOT_PAID.getIndex())) {
            return;
        }
        //上级平级才赠送经验值
        UserEntity userEntity = userDao.get(orderEntity.getUserId());
//        LevelEntity userLevel = levelDao.findByUserId(userEntity.getId());
//        if (userEntity.getPid() != Const.ADMIN_ID) {
//            LevelEntity topLevel = levelDao.findByUserId(userEntity.getPid());
//            if(topLevel.getLv()==userLevel.getLv()){
//                sumNoAgentExp(orderEntity, userEntity);
//            }
//        }
        //送给自己
        accountService.rewardExp(orderEntity.getUserId(), orderEntity.getPrice(), orderEntity.getOrderNo(), userEntity.getName(), true);
        accountService.rewardEqlExp(orderEntity.getUserId(), orderEntity.getPrice(), orderEntity.getOrderNo(), userEntity.getName(), true);
        //其它活动
        // Boolean hasLevelUpAct = false;
        List<OrderItemEntity> itemEntities = itemDao.findByOrderId(orderEntity.getId());
        for (OrderItemEntity itemEntity : itemEntities) {
            MallGoodsEntity goods = this.mallGoodsDao.get(itemEntity.getGoodsId());

            if (goods != null && goods.getSaleType() != null && goods.getSaleType().equals(MallGoodsSaleTypeEnum.LOTTERY.getIndex())) {
                return;
            }

            SaleTypeInfoEntity saleTypeInfoEntity = saleTypeInfoDao.findByGoodsId(itemEntity.getGoodsId());
            if (saleTypeInfoEntity == null) {
                return;
            }

            //给予代金券
            if (saleTypeInfoEntity.getCashReward() != null && !saleTypeInfoEntity.getCashReward().equals("")) {
                rewardShare(orderEntity.getUserId(), orderEntity.getOrderNo(), itemEntity.getQuantity(), saleTypeInfoEntity.getCashReward(), AccountTypeEnum.CASH.getIndex(), saleTypeInfoEntity.getCashType());
            }
            //给予换购券
            if (saleTypeInfoEntity.getVoucherReward() != null && !saleTypeInfoEntity.getVoucherReward().equals("")) {
                rewardShare(orderEntity.getUserId(), orderEntity.getOrderNo(), itemEntity.getQuantity(), saleTypeInfoEntity.getVoucherReward(), AccountTypeEnum.VOUCHER.getIndex(), saleTypeInfoEntity.getVoucherType());
            }
            // 给予优惠券
            if (saleTypeInfoEntity.getCouponReward() != null && !saleTypeInfoEntity.getCouponReward().equals("")) {
                rewardShare(orderEntity.getUserId(), orderEntity.getOrderNo(), itemEntity.getQuantity(), saleTypeInfoEntity.getCouponReward(), AccountTypeEnum.COUPON.getIndex(), saleTypeInfoEntity.getCouponType());
            }
            // 给予积分
            if (saleTypeInfoEntity.getPointReward() != null && !saleTypeInfoEntity.getPointReward().equals("")) {
                rewardShare(orderEntity.getUserId(), orderEntity.getOrderNo(), itemEntity.getQuantity(), saleTypeInfoEntity.getPointReward(), AccountTypeEnum.POINT.getIndex(), saleTypeInfoEntity.getPointType());
            }
            // 给予区域
            if (saleTypeInfoEntity.getAreaReward() != null && !saleTypeInfoEntity.getAreaReward().equals("")) {
                fireAreaAct(orderEntity.getOrderNo(), orderEntity.getProvince(), orderEntity.getCity(), orderEntity.getCounty(), itemEntity.getQuantity(), saleTypeInfoEntity.getAreaType(), orderEntity.getUserId(), saleTypeInfoEntity.getAreaReward(), goods);
            }
            // 清货券奖励
            if (saleTypeInfoEntity.getClearReward() != null && !saleTypeInfoEntity.getClearReward().equals("")) {
                rewardShare(orderEntity.getUserId(), orderEntity.getOrderNo(), itemEntity.getQuantity(), saleTypeInfoEntity.getClearReward(), AccountTypeEnum.CLEAR.getIndex(), saleTypeInfoEntity.getClearType());
            }
            //给予店铺清货券
            if (orderEntity.getOrderType() == MallOrderOrderTypeEnum.DELIVERY.getIndex()) {
                if (saleTypeInfoEntity.getMaxClear() != null && saleTypeInfoEntity.getMaxClear().compareTo(new BigDecimal(BigInteger.ZERO)) == 1) {
                    AccountRecordEntity recordEntity = new AccountRecordEntity(Const.ADMIN_ID, orderEntity.getFromUserId(), AccountTypeEnum.CLEAR.getIndex(), saleTypeInfoEntity.getMaxClear(), null, null, new Date(), userDao.get(orderEntity.getUserId()).getName() + Const.BUY_ORDER_NO + orderEntity.getOrderNo(), AccountRecordStatusEnum.WAIT.getIndex(), AccountRecordBusEnum.SHOP.getIndex());
                    accountRecordDao.save(recordEntity);
                }
            }

            //抽奖活动
            MallActEntity actEntity = mallActDao.findByGoodsIdAndstatus(itemEntity.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
            //判断是否绑定了抽奖活动
            if (actEntity != null && actEntity.getBindLotteryId() != null
                    && actEntity.getQuantity() != null && itemEntity.getQuantity() != null && actEntity.getOpen()) {
                LotteryActEntity lotteryActEntity = lotteryActDao.findIdByStatus(actEntity.getBindLotteryId());
                if (lotteryActEntity != null) {
                    int count = itemEntity.getQuantity() / actEntity.getQuantity();
                    if (count > 0 && lotteryActEntity.getStartTime() != null) {
//                        info = "活动将于" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(lotteryActEntity.getStartTime()) + "开始";
                        for (int i = 0; i < count; i++) {
                            LotteryRecordEntity lotteryRecordEntity = new LotteryRecordEntity(orderEntity.getUserId(), lotteryActEntity.getId(), orderEntity.getOrderNo(), new Date());
                            lotteryRecordDao.save(lotteryRecordEntity);
                        }
                    }

                }
            }
            /* 升级活动
            if (mallActEntity.getName().equals(Const.LEVEL_UP_ACT)) {
                hasLevelUpAct = true;
            }*/

        }
        ;
      /*  // 有升级活动
        if (hasLevelUpAct) {
            fireLevelUpAct(orderEntity.getUserId());
        }*/
    }

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private StoresService storesService;



    /**
     * 获取提货卡可抵扣价格
     *
     * @param orderEntity
     * @return
     */
    public BigDecimal getCardPrice(MallOrderEntity orderEntity) {
        if (!isMallCardAct(orderEntity)) {
            return BigDecimal.ZERO;
        }
        if (orderEntity.getRemark() == null || orderEntity.getRemark().equals("")) {
            return BigDecimal.ZERO;
        }

        //是礼品专区的产品
        MallCardEntity mallCardEntity = mallCardDao.findByCode(orderEntity.getRemark());
        //提货卡不存在  这里不需要判断是否已经使用 在提交订单的时候卡已经是已经用掉状态了
        if (mallCardEntity == null) {
            return BigDecimal.ZERO;
        }
        if (mallCardEntity.getUserId() != null) {
            return BigDecimal.ZERO;
        }
        if (mallCardEntity.getPrice() == null) {
            mallCardEntity.setPrice(BigDecimal.ZERO);
        }
        //活动卡有效
        return mallCardEntity.getPrice();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void useCard(MallOrderEntity orderEntity) {
        if (!isMallCardAct(orderEntity)) return;
        useCard(orderEntity.getRemark(), orderEntity.getUserId());
    }


    private Boolean isMallCardAct(MallOrderEntity orderEntity) {
        List<OrderItemEntity> items = itemDao.findByOrderId(orderEntity.getId());
        MallCardEntity card = this.mallCardDao.findByCode(orderEntity.getRemark());
        for (OrderItemEntity itemEntity : items) {
            MallGoodsEntity goods = mallGoodsDao.get(itemEntity.getGoodsId());
            if (card != null && card.getGoodsName() != null && !card.getGoodsName().equals(goods.getName())) {
                throw new RRException("您使用的提货卡不能提取该商品");
            }
            if (goods.getSaleType().equals(MallGoodsSaleTypeEnum.CARD.getIndex())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 使用提货卡
     */
    private void useCard(String code, Long userId) {
        MallCardEntity mallCardEntity = mallCardDao.findByCode(code);
        if (mallCardEntity != null) {

            mallCardEntity.setUserId(userId);
            mallCardEntity.setUpdateTime(new Date());
            mallCardDao.update(mallCardEntity);
        }
    }


    @Override
    public String useTicket(MallOrderEntity orderEntity, BigDecimal cardPrice, Long recordId) {
        //总积分
        BigDecimal totalPoint = new BigDecimal(0);
        //总优惠券
        BigDecimal totalCoupon = new BigDecimal(0);
        //总清货券
        BigDecimal totalClear = new BigDecimal(0);
        //总换购券
        BigDecimal totalVoucher = new BigDecimal(0);
        List<OrderItemEntity> itemEntities = itemDao.findByOrderId(orderEntity.getId());
        String info = "";
        for (OrderItemEntity item : itemEntities) {
            TicketVo ticketVo = getTicketVo(item.getGoodsId());
            BigDecimal quantity = new BigDecimal(item.getQuantity());
            MallGoodsEntity mallGoodsEntity = this.mallGoodsDao.get(item.getGoodsId());
            // 如果是奖品售卖类型，并且抽奖记录没有兑换
            if (mallGoodsEntity != null && mallGoodsEntity.getSaleType() != null && mallGoodsEntity.getSaleType().equals(MallGoodsSaleTypeEnum.LOTTERY.getIndex())) {
                LotteryRecordEntity lotteryRecordEntity = lotteryRecordDao.get(recordId);
                if (lotteryRecordEntity.getIsLottery() != null && lotteryRecordEntity.getIsLottery().equals(LotteryRecordStatusEnum.LOTTERY.getIndex()) && lotteryRecordEntity.getStatus().equals(LotteryRecordStatusEnum.NOT_LOTTERY.getIndex())) {
                    lotteryRecordEntity.setStatus(LotteryRecordStatusEnum.LOTTERY.getIndex());
                    lotteryRecordEntity.setOrderId(orderEntity.getId());
                    lotteryRecordDao.update(lotteryRecordEntity);
                    orderEntity.setPrice(BigDecimal.ZERO);
                    mallOrderDao.update(orderEntity);
                } else {
                    throw new RRException("你没有中奖或你的奖品已兑换");
                }
            }

            //累计总积分
            totalPoint = totalPoint.add(quantity.multiply(ticketVo.getPoint()));
            //累计总优惠券
            totalCoupon = totalCoupon.add(quantity.multiply(ticketVo.getCoupon()));
            //累计总换购券
            totalVoucher = totalVoucher.add(quantity.multiply(ticketVo.getVoucher()));
            //累计总清货券
            totalClear = totalClear.add(quantity.multiply(ticketVo.getClear()));
        }
        //提货卡可以抵扣卷
        if (cardPrice.compareTo(orderEntity.getCard()) < 0 && cardPrice.compareTo(BigDecimal.ZERO) > 0) {
            orderEntity.setCard(cardPrice);
            cardPrice = BigDecimal.ZERO;
        } else if (cardPrice.compareTo(orderEntity.getCard()) >= 0) {
            cardPrice = cardPrice.subtract(orderEntity.getCard());
        } else {
            orderEntity.setCard(BigDecimal.ZERO);
        }
        for (OrderItemEntity itemEntity : itemEntities) {
            MallGoodsEntity goods = mallGoodsDao.get(itemEntity.getGoodsId());
            if (goods != null && goods.getSaleType().equals(MallGoodsSaleTypeEnum.CARD.getIndex()) && orderEntity.getCard().equals(BigDecimal.ZERO)) {
                orderEntity.setRemark("");
            }
        }
        //扣减积分
        BigDecimal tem = cutTicket(orderEntity.getOrderNo(), orderEntity.getUserId(), AccountTypeEnum.POINT.getIndex(), totalPoint);
        orderEntity.setPoint(tem);
        //扣减优惠券
        tem = cutTicket(orderEntity.getOrderNo(), orderEntity.getUserId(), AccountTypeEnum.COUPON.getIndex(), totalCoupon);
        orderEntity.setCoupon(tem);
        //扣减换购券
        tem = cutTicket(orderEntity.getOrderNo(), orderEntity.getUserId(), AccountTypeEnum.VOUCHER.getIndex(), totalVoucher);
        orderEntity.setVoucher(tem);
        //扣减清货券
        tem = cutTicket(orderEntity.getOrderNo(), orderEntity.getUserId(), AccountTypeEnum.CLEAR.getIndex(), totalClear);
        orderEntity.setClear(tem);
        return info;
    }


    @Autowired
    private MallOrderDao mallOrderDao;

    @Override
    public void validateSend(ItemVo itemVo, Integer orderType, Long fromUserId, Long toUserId) {
        // MallActEntity actEntity = findByGoodsIdAndstatus(itemVo.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
        MallGoodsEntity goodsEntity = mallGoodsDao.get(itemVo.getGoodsId());
        SaleTypeInfoEntity saleTypeInfoEntity = saleTypeInfoDao.findByGoodsId(itemVo.getGoodsId());
        if (saleTypeInfoEntity == null) return;

        //如果是发货 产品库存不足不允许发货
        if (orderType == MallOrderOrderTypeEnum.DELIVERY.getIndex() && goodsEntity.getStock() < itemVo.getQuantity()) {
            throw new RRException("产品库存不足");
        }

        //零售产品不可以转货
        if (orderType != MallOrderOrderTypeEnum.DELIVERY.getIndex() && MallGoodsSaleTypeEnum.AGENT.getIndex() != goodsEntity.getSaleType()) {
            throw new RRException(goodsEntity.getName() + "禁止转货!");
        }

        //与管理员的操作无需验证
        if (fromUserId.equals(Const.ADMIN_ID) || toUserId.equals(Const.ADMIN_ID)) {
            return;
        }
        //转货
        if (orderType == MallOrderOrderTypeEnum.TRANSFER.getIndex()) {
            //转货限制
            if (YesNoEnum.yes.getIndex() != saleTypeInfoEntity.getTransfer()) {
                throw new RRException(goodsEntity.getName() + "禁止转货!");
            }
        }
        //限制发货
        if (YesNoEnum.yes.getIndex() != saleTypeInfoEntity.getDelivery() && orderType == MallOrderOrderTypeEnum.DELIVERY.getIndex()) {
            throw new RRException(goodsEntity.getName() + "禁止发货!");
        }
    }

    @Autowired
    private LotteryRecordDao lotteryRecordDao;

    @Override
    public MallActEntity findByName(String name) {
        return mallActDao.findByName(name);
    }

    @Autowired
    private MallSkuDao mallSkuDao;
    @Autowired
    private SaleTypeInfoDao saleTypeInfoDao;

    @Override
    public void validateCommit(Long userId, String remark, ItemVo itemVo, List<? extends ItemVo> itemVos, Integer orderType, Long recordId) {
        //存在活动查看活动存在的一些限制
        MallGoodsEntity goodsEntity = mallGoodsDao.get(itemVo.getGoodsId());
        MallActEntity actEntity = findByGoodsIdAndstatus(itemVo.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
        SaleTypeInfoEntity saleTypeInfoEntity = saleTypeInfoDao.findByGoodsId(goodsEntity.getId());
        //奖品验证
        if (goodsEntity != null && goodsEntity.getSaleType().equals(MallGoodsSaleTypeEnum.LOTTERY.getIndex())) {

            if (recordId.equals(null)) {
                throw new RRException("您没有中奖");
            }
            LotteryRecordEntity lotteryRecordEntity = this.lotteryRecordDao.get(recordId);
            if (lotteryRecordEntity != null) {
                if (lotteryRecordEntity.getIsLottery().equals(null)) {
                    throw new RRException("您没有中奖");
                }
                if (lotteryRecordEntity.getIsLottery() != null && !lotteryRecordEntity.getIsLottery().equals(LotteryRecordStatusEnum.LOTTERY.getIndex())) {
                    throw new RRException("您没有抽奖");
                }
                if (lotteryRecordEntity.getGoodsId().equals(goodsEntity.getId())) {
                    throw new RRException("您中的不是这个奖项");
                }
                if (lotteryRecordEntity.getStatus().equals(LotteryRecordStatusEnum.LOTTERY.getIndex())) {
                    throw new RRException("您已兑换奖品");
                }
                if (itemVos.size() > 1) {
                    throw new RRException("请单独下单兑奖!");
                }
                if (itemVos.get(0).getQuantity() > 1) {
                    throw new RRException("一次只能兑一件!");
                }
            } else {
                throw new RRException("您没有中奖");
            }

        }
        if (actEntity != null) {
            if (!actEntity.getOpen()) {
                throw new RRException("活动已结束!");
            }
            if (actEntity.getStock() < itemVo.getQuantity()) {
                throw new RRException("活动库存不足");
            }
        }
        if (orderType == MallOrderOrderTypeEnum.DELIVERY.getIndex() && itemVo.getQuantity() > goodsEntity.getStock()) {
            throw new RRException(goodsEntity.getName() + "库存不足!最多可购买X" + goodsEntity.getStock() + "或可将产品转入库存");
        }
        // 产品库存数量不足 是可预订状态则可以转入库存 仅限于代理有利产品
        if (orderType == MallOrderOrderTypeEnum.TRANSFER.getIndex() && itemVo.getQuantity() > goodsEntity.getStock() && (goodsEntity.getReserve() == null || goodsEntity.getReserve() != MallGoodsReserveEnum.YES.getIndex())) {
            throw new RRException(goodsEntity.getName() + "库存不足!最多可购买X" + goodsEntity.getStock());
        }

        MallSkuEntity mallSkuEntity = this.mallSkuDao.queryNameAndGoodsId(itemVo.getSkuName(), goodsEntity.getId());
        if (mallSkuEntity != null && mallSkuEntity.getDisable()) {
            throw new RRException("该规格已禁用");
        }

        //判断积分是否足够  quequnlong
        if (saleTypeInfoEntity.getPoint() != null && !saleTypeInfoEntity.getPoint().equals(BigDecimal.ZERO)) {
            AccountEntity accountPoint = accountService.findByUserIdAndType(userId, AccountTypeEnum.POINT.getIndex()); //根据id和类别查询账户信息(积分)
            if (accountPoint.getAmount().compareTo(saleTypeInfoEntity.getPoint()) == -1) {
                throw new RRException("积分不足,购买产品需要" + saleTypeInfoEntity.getPoint() + "积分");
            }
        }

        //转货
        if (orderType == MallOrderOrderTypeEnum.TRANSFER.getIndex()) {
            //转货限制
            if (YesNoEnum.yes.getIndex() != saleTypeInfoEntity.getTransfer() && MallOrderOrderTypeEnum.TRANSFER.getIndex() == orderType) {
                throw new RRException(goodsEntity.getName() + "禁止转货!");
            }
            //零售产品不可以转货
            if (MallGoodsSaleTypeEnum.AGENT.getIndex() != goodsEntity.getSaleType()) {
                throw new RRException(goodsEntity.getName() + "禁止转货!");
            }
            //第三方代理有利不可以转货
            /*if (goodsEntity.getSaleType() != null
                    && goodsEntity.getSaleType().equals(MallGoodsSaleTypeEnum.AGENT.getIndex())
                    && goodsEntity.getUserId() != null) {
                throw new RRException(goodsEntity.getName() + "禁止转货!");

            }*/

        }
        //限制发货
        if (YesNoEnum.yes.getIndex() != saleTypeInfoEntity.getDelivery() && orderType == MallOrderOrderTypeEnum.DELIVERY.getIndex()) {
            throw new RRException(goodsEntity.getName() + "禁止发货!");
        }
        //捆绑销售
        //如果是打开状态则不去查找捆绑
        // List<MallActEntity> actEntityList = mallActDao.findByBindGoodsId(itemVo.getGoodsId());
        MallActEntity mallActEntity = mallActDao.findByGoodsIdAndstatus(itemVo.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
        if (mallActEntity != null && mallActEntity.getBindGoodsQuantity() != null) {
            Boolean bindPass = false;
            String name = "";
            //级别限购
            if (mallActEntity.getLevel() != null) {
                LevelEntity level = levelService.findByUserId(userId,goodsEntity.getAuth());
                if (mallActEntity.getLevel().contains(level.getName())) {
                    throw new RRException("当前级别不可以购买!");
                }
            }
            for (ItemVo item : itemVos) {
                //主产品绑定了数量
                if (item.getGoodsId().equals(mallActEntity.getBindGoodsId())) {
                    if (mallActEntity.getFirstGoodsQuantity() != null && mallActEntity.getFirstGoodsQuantity() > 0) {
                        if (itemVo.getQuantity() != mallActEntity.getFirstGoodsQuantity() && itemVo.getQuantity() % mallActEntity.getFirstGoodsQuantity() != 0) {
                            throw new RRException(goodsEntity.getName() + "为活动产品,必须购买活动初始数量或数量的倍数");
                        }
                        //购买必须小于捆绑产品的倍数
                        if (itemVo.getQuantity() <= item.getQuantity() / mallActEntity.getBindGoodsQuantity() * mallActEntity.getFirstGoodsQuantity() && item.getQuantity() >= mallActEntity.getBindGoodsQuantity()) {
                            // if (item.getQuantity() >= itemVo.getQuantity() / mallActEntity.getFirstGoodsQuantity() * mallActEntity.getBindGoodsQuantity() && itemVo.getQuantity() >= mallActEntity.getFirstGoodsQuantity()) {
                            bindPass = true;
                            break;
                        }
                    } else {
                        //旧捆绑方式
                        if (item.getQuantity() >= itemVo.getQuantity() * mallActEntity.getBindGoodsQuantity()) {
                            bindPass = true;
                            break;
                        }
                    }
                }
            }
            String goodsName = mallGoodsDao.get(mallActEntity.getBindGoodsId()).getName();
            int number = mallActEntity.getFirstGoodsQuantity() != null && mallActEntity.getFirstGoodsQuantity() > 0 ? (itemVo.getQuantity() / mallActEntity.getBindGoodsQuantity()) * mallActEntity.getFirstGoodsQuantity() : itemVo.getQuantity() * mallActEntity.getBindGoodsQuantity();
            name = name + goodsName + "X" + number + "/";
              /*  if (bindPass) {
                    break;
                }*/
            //如果不通过
            if (!bindPass) {
                // MallGoodsEntity goodsEntity1 = mallGoodsDao.get(mallActEntity.getBindGoodsId());
                throw new RRException("购买" + itemVo.getQuantity() + "X" + goodsEntity.getName() + "需要购买" + name);
            }
        }

        if (actEntity == null) return;


        //提货卡活动验证
     /*   if (actEntity.getName().equals(Const.MALL_CARD_ACT)) {
            if (itemVos.size() > 1) {
                throw new RRException("请单独下单提货!");
            }
            if (itemVos.get(0).getQuantity() > 1) {
                throw new RRException("一次只能提一件!");
            }
            if (remark == null || remark.equals("")) {
                throw new RRException("请输入提货卡");
            }
            MallCardEntity mallCardEntity = mallCardDao.findByCode(remark.trim());
            if (mallCardEntity == null) {
                throw new RRException("提货卡无效");
            }
            if (mallCardEntity.getUserId() != null) {
                throw new RRException("提货卡已被使用!");
            }
        }*/
        //级别限购
//        if (actEntity.getLevel() != null) {
//            LevelEntity level = levelDao.findByUserId(userId);
//            if (actEntity.getLevel().contains(level.getName())) {
//                throw new RRException("当前级别不可以购买!");
//            }
//        }
        //限购数量
        if (actEntity.getNumber() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            String format = sdf.format(new Date());
            Integer number = mallActDao.sumUserBuyNumber(actEntity.getStart(), actEntity.getEnd(), itemVo.getGoodsId(), userId, format);
            if (number == null) number = 0;
            number += itemVo.getQuantity();
            if (number > actEntity.getNumber()) {
                throw new RRException(goodsEntity.getName() + "限购:" + actEntity.getNumber());
            }
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(MallOrderEntity orderEntity) {
        //如果是提货卡活动 重制提货卡 不需要支付
        if (isMallCardAct(orderEntity)) {
            reviewCard(orderEntity.getRemark());
        }
        //没有支付的不管
        if (orderEntity.getPayStatus() == null || orderEntity.getPayStatus().equals(MallOrderPayStatusEnum.NOT_PAID.getIndex())) {
            return;
        }
        //判断是否有升级活动
        List<OrderItemEntity> itemEntities = itemDao.findByOrderId(orderEntity.getId());
        Boolean hasLevelUpAct = false;
        for (OrderItemEntity itemEntity : itemEntities) {
            MallActEntity mallActEntity = mallActDao.findByGoodsIdAndstatus(itemEntity.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
            // 活动不存在
            if (mallActEntity == null) {
                return;
            }
            // 存在升级活动
            if (mallActEntity.getName().equals(Const.LEVEL_UP_ACT)) {
                hasLevelUpAct = true;
                break;
            }
        }
        // 取消升级
//        if (hasLevelUpAct) {
//            cancelLevelUpAct(orderEntity.getUserId());
//        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void untieAct(Long id, Integer status) {
        mallActDao.untieAct(id, status);

    }

    @Override
    public List<MallActEntity> list(Map<String, Object> params) {
        return mallActDao.list(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoUntieAct() {
        List<MallActEntity> actEntities = mallActDao.findByNowTime(new Date());
        for (MallActEntity actEntity : actEntities) {
            mallActDao.untieAct(actEntity.getId(), MallActStatusEnum.CLOSED.getIndex());
        }
    }
}